package com.dingding.transfer.stamper.handler;

import com.alibaba.fastjson.JSONObject;
import com.dingding.transfer.stamper.constant.ApprovalPara;
import com.dingding.transfer.stamper.dto.BaseResult;
import com.dingding.transfer.stamper.entity.CompInfo;
import com.dingding.transfer.stamper.entity.ProcessDetail;
import com.dingding.transfer.stamper.service.BusinessService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author wangxiyuan
 * @description
 * @createDate 2021/4/6 15:19
 **/
@Component
@Slf4j
public class UseStamperInstance implements TaskInstanceProcessor{
    private int status = ApprovalPara.ApprovalEnum.APPLY_START.getTaskStatus();

    @Autowired
    private BusinessService businessService;

    @Override
    public boolean match(String name) {
        return StringUtils.contains(name, ApprovalPara.STAMPER_INFO);
    }

    @Override
    public void handleTaskStart(JSONObject jsonObject) {
        log.info("用印审批回调");
        ProcessDetail processDetail = ApprovalPara.buildDetail(jsonObject);
        try {
//            User userInfo = businessService.findUserInfo(processDetail.getUserid());
//            processDetail.setUserid(userInfo.getSerialId().toString());
            processDetail.setStatus(status);
            CompInfo compInfo = businessService.getCompInfo(jsonObject.getString("corpId"));
            processDetail.setCompId(compInfo.getCompId());
        } catch (Exception e) {
            log.error("根据钉钉企业Id{}找不到对应的公司，原因为{}",jsonObject.getString("corpId"),e.getMessage());
        }
        // 保存申请单
        businessService.saveProcessDetail(processDetail);
    }

    @Override
    public void handleTaskTerminate(JSONObject jsonObject) {
        status = ApprovalPara.ApprovalEnum.APPLY_CANCEL.getTaskStatus();
    }

    @Override
    public void handleTaskEnd(JSONObject jsonObject) {
        if(ApprovalPara.RESULT_AGREE.equals(jsonObject.getString("result"))){
            status = ApprovalPara.ApprovalEnum.APPLY_AGREE.getTaskStatus();
        }else if (ApprovalPara.RESULT_REFUSE.equals(jsonObject.getString("result"))){
            status = ApprovalPara.ApprovalEnum.APPLY_REJECT.getTaskStatus();
        }
    }

    @Override
    public void customHandle(JSONObject jsonObject) {
        if(!ApprovalPara.TASK_START.equals(jsonObject.getString("type"))){
            String processId = jsonObject.getString("processInstanceId");
            String corpId = jsonObject.getString("corpId");
            BaseResult baseResult = businessService.batchSaveProcessContent(corpId,processId);
            if(baseResult.isSuccess()){
                // 更新审批流程的状态
                businessService.updateProcessStatus(processId,status);
            }
        }
    }
}
